// pages/process/process.js
const app = getApp();
const auth = require('../../utils/auth.js');
const http = require('../../utils/http.js');
const config = require('../../config.js');

Page({
  data: {
    type: 0, // 0: 普通版本, 1: 专业版本
    isUploading: false,
    isProcessing: false,
    progress: 0,
    fileInfo: null,
    result: null,
    errorMsg: '',
    showLinkInput: false,
    showAudioUrlInput: false, // 显示音频URL输入框
    videoLink: '',
    audioUrl: '', // 音频文件URL
    taskInfo: null, // 任务信息
    transcribing: false, // 是否正在转写中
    languageIndex: 0,
    languages: [
      { code: 'zh', name: '中文（普通话）' },
      { code: 'en', name: '英语' },
      { code: 'yue', name: '粤语' },
      { code: 'ja', name: '日语' },
      { code: 'ko', name: '韩语' },
      { code: 'vi', name: '越南语' },
      { code: 'ms', name: '马来语' },
      { code: 'id', name: '印度尼西亚语' },
      { code: 'fil', name: '菲律宾语' },
      { code: 'th', name: '泰语' },
      { code: 'fr', name: '法语' },
      { code: 'de', name: '德语' },
      { code: 'es', name: '西班牙语' },
      { code: 'it', name: '意大利语' },
      { code: 'ru', name: '俄语' }
    ],
    uploadOptions: {
      free: {
        title: '普通版本',
        description: '每天免费处理一个文件',
        maxSize: '200MB',
        maxDuration: '2小时',
        supportedFormats: ['mp3', 'wav', 'mp4', 'flac', 'ogg', 'm4a']
      },
      professional: {
        title: '专业版本',
        description: '更专业，更多特性',
        maxSize: '5GB',
        maxDuration: '5小时',
        supportedFormats: ['mp3', 'wav', 'mp4', 'flac', 'ogg', 'm4a', 'wma', 'aac']
      }
    }
  },

  onLoad: function(options) {
    // 检查登录状态
    const isLoggedIn = auth.checkLoginStatus();
    if (!isLoggedIn) {
      wx.showModal({
        title: '提示',
        content: '需要登录才能使用此功能',
        showCancel: false,
        success: () => {
          wx.navigateBack();
        }
      });
      return;
    }

    // 获取类型参数
    if (options.type) {
      this.setData({
        type: parseInt(options.type)
      });
    }
  },

  // 语言选择变化
  onLanguageChange: function(e) {
    this.setData({
      languageIndex: e.detail.value
    });
  },

  // 选择微信聊天文件
  chooseWechatFile: function() {
    if (this.data.isUploading || this.data.isProcessing) {
      return;
    }

    wx.showActionSheet({
      itemList: ['微信聊天视频', '微信聊天音频'],
      success: (res) => {
        if (res.tapIndex === 0) {
          // 选择视频
          wx.chooseMessageFile({
            count: 1,
            type: 'video',
            success: (res) => {
              this.handleSelectedFile(res.tempFiles[0]);
            }
          });
        } else if (res.tapIndex === 1) {
          // 选择音频
          wx.chooseMessageFile({
            count: 1,
            type: 'file',
            extension: ['mp3', 'wav', 'flac', 'ogg', 'm4a'],
            success: (res) => {
              this.handleSelectedFile(res.tempFiles[0]);
            }
          });
        }
      }
    });
  },

  // 选择手机相册视频
  chooseVideoFromAlbum: function() {
    if (this.data.isUploading || this.data.isProcessing) {
      return;
    }

    wx.chooseMedia({
      count: 1,
      mediaType: ['video'],
      sourceType: ['album'],
      success: (res) => {
        this.handleSelectedFile({
          name: res.tempFiles[0].tempFilePath.split('/').pop(),
          size: res.tempFiles[0].size,
          path: res.tempFiles[0].tempFilePath
        });
      }
    });
  },

  // 选择本地录音文件
  chooseAudioFile: function() {
    if (this.data.isUploading || this.data.isProcessing) {
      return;
    }

    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      extension: ['mp3', 'wav', 'flac', 'ogg', 'm4a', 'wma', 'aac'],
      success: (res) => {
        const file = res.tempFiles[0];
        // 确保文件对象包含tempFilePath属性
        if (!file.tempFilePath && file.path) {
          file.tempFilePath = file.path;
        }
        this.handleSelectedFile(file);
      }
    });
  },

  // 输入视频链接
  inputVideoLink: function() {
    if (this.data.isUploading || this.data.isProcessing || this.data.transcribing) {
      return;
    }

    wx.showActionSheet({
      itemList: ['在线短视频链接', '普通视频链接'],
      success: (res) => {
        if (res.tapIndex === 0) {
          // 在线短视频链接 - 需要输入音频URL
          this.setData({
            showAudioUrlInput: true,
            audioUrl: ''
          });
        } else if (res.tapIndex === 1) {
          // 普通视频链接
          this.setData({
            showLinkInput: true,
            videoLink: ''
          });
        }
      }
    });
  },

  // 音频URL输入变化
  onAudioUrlInput: function(e) {
    this.setData({
      audioUrl: e.detail.value
    });
  },

  // 确认音频URL
  confirmAudioUrl: function() {
    if (!this.data.audioUrl) {
      wx.showToast({
        title: '请输入音频文件URL',
        icon: 'none'
      });
      return;
    }

    // 验证链接格式
    const urlPattern = /^(https?:\/\/)([\da-z.-]+)\.([a-z.]{2,6})([/\w.-]*)*\/?$/;
    if (!urlPattern.test(this.data.audioUrl)) {
      wx.showToast({
        title: '请输入有效的URL',
        icon: 'none'
      });
      return;
    }

    // 直接提交音频URL进行转写
    this.processAudioUrl();
  },

  // 取消音频URL输入
  cancelAudioUrlInput: function() {
    this.setData({
      showAudioUrlInput: false,
      audioUrl: ''
    });
  },

  // 视频链接输入变化
  onVideoLinkInput: function(e) {
    this.setData({
      videoLink: e.detail.value
    });
  },

  // 确认视频链接
  confirmVideoLink: function() {
    if (!this.data.videoLink) {
      wx.showToast({
        title: '请输入视频链接',
        icon: 'none'
      });
      return;
    }

    // 验证链接格式
    const urlPattern = /^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([/\w.-]*)*\/?$/;
    if (!urlPattern.test(this.data.videoLink)) {
      wx.showToast({
        title: '请输入有效的链接',
        icon: 'none'
      });
      return;
    }

    this.setData({
      fileInfo: {
        name: '在线视频',
        size: '未知',
        path: this.data.videoLink,
        isLink: true
      },
      showLinkInput: false
    });
  },

  // 取消视频链接输入
  cancelVideoLinkInput: function() {
    this.setData({
      showLinkInput: false,
      videoLink: ''
    });
  },

  // 处理音频URL转写
  processAudioUrl: async function() {
    this.setData({
      isUploading: true,
      progress: 0,
      errorMsg: '',
      showAudioUrlInput: false
    });

    try {
      wx.showLoading({
        title: '提交中...',
        mask: true
      });

      // 使用GET请求提交音频URL
      console.log('音频URL提交，使用GET方法调用:', config.API.PROCESS_AUDIO);

      const response = await http.get(config.API.PROCESS_AUDIO, {
        audioUrl: this.data.audioUrl,
        language: this.data.languages[this.data.languageIndex].code,
        type: this.data.type
      });

      wx.hideLoading();
      console.log('GET请求响应:', response);

      // 检查新的响应格式
      if (response.code === 200 && response.data && response.data.code === 0) {
        // 接口调用成功
        this.setData({
          isUploading: false,
          transcribing: true,
          taskInfo: {
            taskId: response.data.taskId,
            requestId: response.data.requestId
          },
          audioUrl: ''
        });

        // 显示转写中提示
        this.showTranscribingStatus();
      } else {
        // 接口调用失败
        this.setData({
          isUploading: false,
          errorMsg: response.message || '提交失败，请重试'
        });
      }
    } catch (error) {
      wx.hideLoading();
      console.error('提交音频URL失败:', error);
      this.setData({
        isUploading: false,
        errorMsg: error.message || '网络错误，请重试'
      });
    }
  },

  // 显示转写中状态
  showTranscribingStatus: function() {
    wx.showModal({
      title: '转写任务已提交',
      content: '正在转写中，请稍等结果或继续提交转写文件',
      showCancel: true,
      cancelText: '继续提交',
      confirmText: '查看结果',
      confirmColor: '#07C160', // 亮一点的颜色
      success: (res) => {
        if (res.confirm) {
          // 查看结果 - 跳转到历史记录或结果页面
          this.viewTaskResult();
        } else if (res.cancel) {
          // 继续提交 - 重置状态
          this.resetForNewSubmission();
        }
      }
    });
  },

  // 查看任务结果
  viewTaskResult: function() {
    if (this.data.taskInfo && this.data.taskInfo.taskId) {
      // 跳转到历史记录页面，携带任务ID参数
      wx.switchTab({
        url: '/pages/history/history',
        success: () => {
          // 可以在历史记录页面中处理taskId参数
          console.log('跳转到历史记录页面，任务ID:', this.data.taskInfo.taskId);
        }
      });
    } else {
      // 没有任务信息，直接跳转到历史记录
      wx.switchTab({
        url: '/pages/history/history'
      });
    }
  },

  // 重置为新提交
  resetForNewSubmission: function() {
    this.setData({
      transcribing: false,
      taskInfo: null,
      fileInfo: null,
      result: null,
      errorMsg: ''
    });
  },

  // 处理选择的文件
  handleSelectedFile: function(file) {
    // 检查文件大小
    const maxSize = this.data.type === 0
      ? 200 * 1024 * 1024  // 200MB for free version
      : 5 * 1024 * 1024 * 1024;  // 5GB for professional version

    if (file.size > maxSize) {
      const maxSizeText = this.data.type === 0 ? '200MB' : '5GB';
      wx.showModal({
        title: '文件过大',
        content: `文件大小超过${maxSizeText}限制，请选择较小的文件或使用专业版`,
        showCancel: false
      });
      return;
    }

    // 确保文件对象包含tempFilePath属性
    if (!file.tempFilePath && file.path) {
      file.tempFilePath = file.path;
    }

    this.setData({
      fileInfo: {
        name: file.name,
        size: this.formatFileSize(file.size),
        path: file.path,
        tempFilePath: file.tempFilePath || file.path,
        file: file,
        isLink: false
      },
      showLinkInput: false
    });
  },

  // 上传并处理文件
  uploadAndProcess: async function() {
    if (!this.data.fileInfo || this.data.isUploading || this.data.isProcessing) {
      return;
    }

    this.setData({
      isUploading: true,
      progress: 0,
      errorMsg: ''
    });

    // 处理在线视频链接
    if (this.data.fileInfo.isLink) {
      this.processVideoLink();
      return;
    }

    try {
      wx.showLoading({
        title: '上传中...',
        mask: true
      });

      // 获取文件路径
      const filePath = this.data.fileInfo.file.tempFilePath || this.data.fileInfo.path;
      console.log('准备上传文件:', filePath);
      
      // 使用wx.uploadFile直接上传文件（GET请求）
      const token = wx.getStorageSync('token');
      const uploadTask = wx.uploadFile({
        url: config.BASE_URL + config.API.PROCESS_AUDIO,
        filePath: filePath,
        name: 'file', // 后端接收的文件字段名
        formData: {
          type: this.data.type.toString(),
          language: this.data.languages[this.data.languageIndex].code
        },
        header: {
          'Authorization': token ? `Bearer ${token}` : ''
        },
        success: (res) => {
          wx.hideLoading();
          console.log('文件上传响应:', res);
          
          try {
            const response = JSON.parse(res.data);
            
            // 检查响应格式
            if (response.code === 200 && response.data && response.data.code === 0) {
              // 接口调用成功
              this.setData({
                isUploading: false,
                transcribing: true,
                taskInfo: {
                  taskId: response.data.taskId,
                  requestId: response.data.requestId
                }
              });

              // 显示转写中提示
              this.showTranscribingStatus();
            } else {
              // 接口调用失败
              this.setData({
                isUploading: false,
                errorMsg: response.message || '上传失败，请重试'
              });
            }
          } catch (parseError) {
            console.error('解析响应失败:', parseError);
            this.setData({
              isUploading: false,
              errorMsg: '响应解析失败，请重试'
            });
          }
        },
        fail: (error) => {
          wx.hideLoading();
          console.error('上传文件失败:', error);
          this.setData({
            isUploading: false,
            errorMsg: error.errMsg || '上传失败，请重试'
          });
        }
      });

      // 监听上传进度
      uploadTask.onProgressUpdate((res) => {
        this.setData({
          progress: res.progress
        });
        console.log('上传进度:', res.progress + '%');
      });
      
    } catch (error) {
      wx.hideLoading();
      console.error('上传文件失败:', error);
      this.setData({
        isUploading: false,
        errorMsg: error.message || '上传失败，请重试'
      });
    }
  },



  // 处理视频链接
  processVideoLink: async function() {
    this.setData({
      isUploading: true,
      progress: 0,
      errorMsg: ''
    });

    try {
      wx.showLoading({
        title: '提交中...',
        mask: true
      });

      // 使用GET请求提交视频链接
      console.log('视频链接提交，使用GET方法调用:', config.API.PROCESS_AUDIO);

      const response = await http.get(config.API.PROCESS_AUDIO, {
        videoUrl: this.data.fileInfo.path,
        type: this.data.type,
        language: this.data.languages[this.data.languageIndex].code
      });

      wx.hideLoading();
      console.log('GET请求响应:', response);

      // 检查新的响应格式
      if (response.code === 200 && response.data && response.data.code === 0) {
        // 接口调用成功
        this.setData({
          isUploading: false,
          transcribing: true,
          taskInfo: {
            taskId: response.data.taskId,
            requestId: response.data.requestId
          }
        });

        // 显示转写中提示
        this.showTranscribingStatus();
      } else {
        // 接口调用失败
        this.setData({
          isUploading: false,
          errorMsg: response.message || '处理链接失败，请重试'
        });
      }
    } catch (error) {
      wx.hideLoading();
      console.error('处理视频链接失败:', error);
      this.setData({
        isUploading: false,
        errorMsg: error.message || '处理链接失败，请重试'
      });
    }
  },

  // 轮询处理状态
  pollProcessingStatus: function(taskId) {
    if (!this.data.isProcessing) {
      return;
    }

    http.get('/api/transcribe/status', { taskId: taskId })
      .then(res => {
        if (res.status === 'completed') {
          this.setData({
            isProcessing: false,
            result: res.result
          });

          // 保存到历史记录
          this.saveToHistory(res.result);
        } else if (res.status === 'failed') {
          this.setData({
            isProcessing: false,
            errorMsg: res.message || '处理失败，请重试'
          });
        } else {
          // 更新进度
          this.setData({
            progress: res.progress || this.data.progress
          });

          // 继续轮询
          setTimeout(() => {
            this.pollProcessingStatus(taskId);
          }, 2000);
        }
      })
      .catch(err => {
        this.setData({
          isProcessing: false,
          errorMsg: '获取处理状态失败：' + err.message
        });
      });
  },

  // 保存到历史记录
  saveToHistory: function(result) {
    const historyItem = {
      id: new Date().getTime().toString(),
      fileName: this.data.fileInfo.name,
      fileSize: this.data.fileInfo.size,
      type: this.data.type,
      language: this.data.languages[this.data.languageIndex].name,
      date: new Date().toISOString(),
      result: result
    };

    let history = wx.getStorageSync('transcription_history') || [];
    history.unshift(historyItem);

    // 限制历史记录数量
    if (history.length > 100) {
      history = history.slice(0, 100);
    }

    wx.setStorageSync('transcription_history', history);
  },

  // 复制结果
  copyResult: function() {
    if (!this.data.result) {
      return;
    }

    wx.setClipboardData({
      data: this.data.result,
      success: () => {
        wx.showToast({
          title: '已复制到剪贴板',
          icon: 'success'
        });
      }
    });
  },

  // 重新开始
  restart: function() {
    this.setData({
      isUploading: false,
      isProcessing: false,
      progress: 0,
      fileInfo: null,
      result: null,
      errorMsg: '',
      showLinkInput: false,
      videoLink: ''
    });
  },

  // 查看历史记录
  viewHistory: function() {
    wx.switchTab({
      url: '/pages/history/history'
    });
  },

  // 格式化文件大小
  formatFileSize: function(size) {
    if (size < 1024) {
      return size + 'B';
    } else if (size < 1024 * 1024) {
      return (size / 1024).toFixed(2) + 'KB';
    } else if (size < 1024 * 1024 * 1024) {
      return (size / (1024 * 1024)).toFixed(2) + 'MB';
    } else {
      return (size / (1024 * 1024 * 1024)).toFixed(2) + 'GB';
    }
  }
});
